package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.CurrentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service

public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Employee employee,Long[] ids) {
        if(employee.getId() == null){
            employeeMapper.insert(employee);
        }else{
            employeeMapper.updateByPrimaryKey(employee);
            employeeMapper.deleteEmpAndRoleRelation(employee.getId());
        }

        if(ids !=null){
            for (Long roleId : ids) {
                employeeMapper.insertRoleAndEmpRelation(roleId,employee.getId());
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject queryObject) {
        Integer row = employeeMapper.selectForCount(queryObject);
        if(row == null){
            return PageResult.EMPTY_PAGE;
        }
        List<Employee> data = employeeMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),data,row);
    }

    @Override
    public void login(String username, String password) {
        Employee employee = employeeMapper.login(username,password);
        if(employee == null){
            throw new RuntimeException("账号或者密码错误");
        }

        //将用户放入到session中
        CurrentUtil.setCurrent(employee);
        Set<String> expressions = permissionMapper.selectExpressionsByEmpId(employee.getId());
        CurrentUtil.setExpression(expressions);
    }
}
